package kube

import (
	"gitee.com/lllgo/gopkg/exec"
	"github.com/spf13/cobra"
	"os"
	"path/filepath"
)

func init() {
	registerSubCmd(initCmd())
}

func initCmd() *cobra.Command {
	var (
		isDownload bool
		baseDirs   []string
	)

	var cmd = &cobra.Command{
		Use:   "init",
		Short: "初始化集群配置",
		Long: `生成集群必需的配置文件
ssl和*.kubeconfig文件`,
		RunE: func(cmd *cobra.Command, args []string) error {
			bd, err := filepath.Abs(localBaseDir)
			if err != nil {
				return err
			}

			if _, err := os.Stat(bd); os.IsNotExist(err) {
				_ = os.Mkdir(bd, os.ModePerm)
			}

			if _, err := os.Stat(filepath.Join(bd, "bin")); isDownload || os.IsNotExist(err) {
				// TODO 扩展下载资源属性配置 如：这些资源的版本
				if err := exec.Shell("./download.sh", kubeToolsDir, bd); err != nil {
					return err
				}
			}

			genTmpl()

			if err := exec.Shell("./init.sh", kubeToolsDir, kubeConfig.Dir, bd, kubeConfig.Meta.CertDir); err != nil {
				return err
			}
			return nil
		},
	}
	cmd.PersistentFlags().StringSliceVarP(&baseDirs, "local-base-dir", "", nil, "设置存储生成资源目录，主要针对多集群 e.g. --base-dir base-dir1,base-dir1")
	cmd.PersistentFlags().BoolVarP(&isDownload, "download", "", false, "是否下载依赖的可执行文件")

	return cmd
}
